import json
import os
from typing import Dict, Any, List, Optional, Set

class AdvancedDB:
    """
    更高级的数据库实现，支持索引和简单查询
    """
    
    def __init__(self, db_file: str = 'advanced_db.json'):
        self.db_file = db_file
        self.data: Dict[str, Dict[str, Any]] = {}  # 主存储 {id: record}
        self.indexes: Dict[str, Dict[Any, Set[str]]] = {}  # 索引 {field_name: {value: set(id)}}
        self._load()
    
    def _load(self) -> None:
        """加载数据库"""
        if os.path.exists(self.db_file):
            with open(self.db_file, 'r') as f:
                saved_data = json.load(f)
                self.data = saved_data.get('data', {})
                self.indexes = saved_data.get('indexes', {})
    
    def _save(self) -> None:
        """保存数据库"""
        with open(self.db_file, 'w') as f:
            json.dump({
                'data': self.data,
                'indexes': self.indexes
            }, f, indent=2)
    
    def create_index(self, field: str) -> None:
        """
        为指定字段创建索引
        
        :param field: 字段名
        """
        if field not in self.indexes:
            self.indexes[field] = {}
            for record_id, record in self.data.items():
                value = record.get(field)
                if value is not None:
                    if value not in self.indexes[field]:
                        self.indexes[field][value] = set()
                    self.indexes[field][value].add(record_id)
            self._save()
    
    def insert(self, record: Dict[str, Any], record_id: Optional[str] = None) -> str:
        """
        插入记录
        
        :param record: 记录数据
        :param record_id: 可选记录ID
        :return: 记录ID
        """
        if record_id is None:
            record_id = str(len(self.data) + 1)
        
        self.data[record_id] = record
        
        # 更新索引
        for field, index in self.indexes.items():
            value = record.get(field)
            if value is not None:
                if value not in index:
                    index[value] = set()
                index[value].add(record_id)
        
        self._save()
        return record_id
    
    def find_by_id(self, record_id: str) -> Optional[Dict[str, Any]]:
        """
        通过ID查找记录
        
        :param record_id: 记录ID
        :return: 记录数据或None
        """
        return self.data.get(record_id)
    
    def find_by_field(self, field: str, value: Any) -> List[Dict[str, Any]]:
        """
        通过字段值查找记录
        
        :param field: 字段名
        :param value: 字段值
        :return: 匹配的记录列表
        """
        if field in self.indexes and value in self.indexes[field]:
            return [self.data[record_id] for record_id in self.indexes[field][value]]
        return [record for record in self.data.values() if record.get(field) == value]
    
    def update(self, record_id: str, updates: Dict[str, Any]) -> bool:
        """
        更新记录
        
        :param record_id: 记录ID
        :param updates: 更新字段
        :return: 是否更新成功
        """
        if record_id not in self.data:
            return False
        
        old_record = self.data[record_id]
        
        # 更新索引
        for field, index in self.indexes.items():
            old_value = old_record.get(field)
            new_value = updates.get(field, old_value)
            
            if old_value in index and record_id in index[old_value]:
                index[old_value].remove(record_id)
                if not index[old_value]:  # 清理空集合
                    del index[old_value]
            
            if new_value is not None:
                if new_value not in index:
                    index[new_value] = set()
                index[new_value].add(record_id)
        
        # 更新记录
        self.data[record_id].update(updates)
        self._save()
        return True
    
    def delete(self, record_id: str) -> bool:
        """
        删除记录
        
        :param record_id: 记录ID
        :return: 是否删除成功
        """
        if record_id not in self.data:
            return False
        
        record = self.data[record_id]
        
        # 更新索引
        for field, index in self.indexes.items():
            value = record.get(field)
            if value in index and record_id in index[value]:
                index[value].remove(record_id)
                if not index[value]:  # 清理空集合
                    del index[value]
        
        # 删除记录
        del self.data[record_id]
        self._save()
        return True
    
if __name__ == "__main__":
    # 创建高级数据库实例
    advanced_db = AdvancedDB('my_advanced_db.json')

    # 创建索引
    advanced_db.create_index('name')
    advanced_db.create_index('age')

    # 插入数据
    alice_id = advanced_db.insert({'name': 'Alice', 'age': 30, 'skills': ['Python']})
    bob_id = advanced_db.insert({'name': 'Bob', 'age': 25, 'skills': ['Java']})

    # 查询数据
    print(advanced_db.find_by_id(alice_id))  # 获取Alice的记录
    print(advanced_db.find_by_field('name', 'Bob'))  # 通过名字查找Bob
    print(advanced_db.find_by_field('age', 30))  # 查找年龄30的人

    # 更新数据
    advanced_db.update(alice_id, {'age': 31, 'skills': ['Python', 'SQL']})

    # 删除数据
    advanced_db.delete(bob_id)
